Generics are a new feature in the .Net framework 2.0+ which make it possible to design classes and methods that do not specify data types until the class or method is declared and instantiated by client code.

This page is Framework Specific

By using a generic type parameter you can write a single class that other client code can use without incurring the cost or risk of casts or boxing operations.

In this first example we can see how a method can accept an array of various types and output the values. Without generics you would need to override the method for each data type, causing problems for scalability and custom types.

using System;
using System.Collections.Generic;

class Generics
{
    static void Main(string[] args)
    {
        // create arrays of various types
        int[] intArray = { 1, 2, 3, 4, 5, 6 };
        double[] doubleArray = { 1.0, 2.0, 3.0, 4.0, 5.0 };
        char[] charArray = { 'A', 'B', 'C', 'D', 'E' };

        DisplayArray(intArray);
        DisplayArray(doubleArray);
        DisplayArray(charArray);

        Console.ReadLine();
    }

    // generic method displays array of any type
    static void DisplayArray<E>(E[] array)
    {
        Console.WriteLine("Display array of type " + array.GetType() + ":");
        foreach (E element in array)
            Console.Write(element + " ");
    }
}

You can see how the one method will handle requests for an array of ints, doubles and chars. We can also use reflection and the GetType method to determine the type of array passed into the generic parameter.

In the next example we can see a generic class with a generic method and a generic field. We can create an instance of the class as an int or a string and populate the field and call the method with parameters of the same type as the generic class, but if you create an instance of type int, you cannot assign strings to it.

using System;
using System.Collections.Generic;

class Generics
{
    static void Main(string[] args)
    {
        MyGeneric<int> mygenericint = new MyGeneric<int>();
        mygenericint.GenericField = 13;
        mygenericint.GenericMethod(42);

        MyGeneric<string> mygenericstring = new MyGeneric<string>();
        mygenericstring.GenericField = "xxx";
        mygenericstring.GenericMethod("xxx");

        // These lines will cause a compile error
        MyGeneric<int> mygenericint2 = new MyGeneric<int>();
        mygenericint2.GenericField = "xxx";
        mygenericint2.GenericMethod("xxx");
    }
}

public class MyGeneric<T>
{
    public T GenericField;
    public void GenericMethod(T t)
    {
        Console.WriteLine("GenericMethod parameter type: " + t.GetType());
    }
}

 

Tutorials in this Series